import java.util.PriorityQueue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2022-12-08
 * Time:22:28
 */
class Mytask implements Comparable<Mytask>{
    private Runnable runnable;
    private long time;
    public Mytask(Runnable runnable,long cur){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+cur;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(Mytask o) {
        return (int) (this.time-o.time);
    }
}
class MyTimer{
    private PriorityBlockingQueue<Mytask> queue=new PriorityBlockingQueue();
    public void schedule(Runnable runnable,long delay){
        Mytask task=new Mytask(runnable,delay);
        queue.put(task);
        synchronized (locker){
            locker.notify();
        }
    }
    private Object locker=new Object();
    public MyTimer(){
        Thread thread=new Thread(()->{
            while(true){
                try {
                    synchronized (locker) {
                        Mytask task = queue.take();
                        if (System.currentTimeMillis() > task.getTime()) {
                            task.getRunnable().run();
                        } else {
                            queue.put(task);
                            locker.wait(task.getTime()-System.currentTimeMillis());
                            }
                    }
                } catch(InterruptedException e){
                    throw new RuntimeException(e);
                }
            }

        });
        thread.start();
    }

}
public class Test2 {
    public static void main1(String[] args) {
        Timer timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

            }
        },100);
    }

    public static void main(String[] args) {
        MyTimer timer=new MyTimer();
        timer.schedule(new Runnable(){
            @Override
            public void run() {
                System.out.println("a");
            }
        },3000);
        timer.schedule(new Runnable(){
            @Override
            public void run() {
                System.out.println("b");
            }
        },4000);
        timer.schedule(new Runnable(){
            @Override
            public void run() {
                System.out.println("c");
            }
        },5000);
    }
}
